package com.lc.user.express.ordering;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.lc.user.express.BaseSecondActivity;
import com.lc.user.express.MainActivity;
import com.lc.user.express.R;
import com.lc.user.express.adapter.DriverAdapter;
import com.lc.user.express.app.AppContext;
import com.lc.user.express.httpserver.GetAutoSelectDriver;
import com.lc.user.express.httpserver.GetChooseDiver;
import com.lc.user.express.httpserver.GetChooseDriverInfo;
import com.lc.user.express.httpserver.GetOrderCancel;
import com.lc.user.express.model.DriverModel;
import com.lc.user.express.ordermanagement.OrderManagementFragment;
import com.lc.user.express.utils.GetToast;
import com.lc.user.express.view.dialog.AffirmDialog;
import com.zcx.helper.http.AsyCallBack;
import com.zcx.yun.YunAction;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/4/6.
 */
public class SelectDriverActivity extends BaseSecondActivity {
    public static final String REFRESH = "com.lc.user.express.select.diver.refresh";
    private BroadcastReceiver mReceiver;
    private ListView lv;
    private DriverAdapter adapter;
    private List<DriverModel> list = new ArrayList<>();
    private int tposition = 0;//选择司机位置


    TextView head_left;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_select_driver);
        setTitle("选择司机");
        setRightButtonText("取消订单", 150);
        initView();
        getData();
        registerReceiver();
    }

    private void initView() {
        ((TextView) findViewById(R.id.tv_public)).setOnClickListener(this);
        lv = (ListView) findViewById(R.id.lv);
        adapter = new DriverAdapter(cnt, list);
        //返回按钮
        head_left= (TextView) findViewById(R.id.head_left);
        head_left.setOnClickListener(this);


        lv.setAdapter(adapter);
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                for (int i = 0; i < list.size(); i++) {
                    if (position == i) {
                        list.get(i).setIsSelect(true);
                        tposition = position;
                    } else {
                        list.get(i).setIsSelect(false);
                    }
                }
                adapter.updateListView(list);
            }
        });

    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.tv_public:
                if (tposition == -1) {
                    GetToast.useString(cnt, "请选择司机");
                } else {
                    chooseDiver();
                }
                break;
            case R.id.head_right:
                new AffirmDialog(cnt, "您确定要取消该订单吗？", "取消", "确定", R.style.MyDialog) {
                    @Override
                    protected void onYesClick() {
                        cancelOrder();
                    }
                }.show();
                break;

            case R.id.head_left:
              //  Toast.makeText(cnt, "呵呵哒", Toast.LENGTH_SHORT).show();
                new AffirmDialog(cnt, "您确定要取消该订单吗？", "取消", "确定", R.style.MyDialog) {
                    @Override
                    protected void onYesClick() {
                        cancelOrder();
                    }
                }.show();
                break;

        }
    }

    private void cancelOrder() {
        new GetOrderCancel(AppContext.myPreferences.getUid(), getIntent().getStringExtra("orderid"), new AsyCallBack<Object>() {
            @Override
            public void onSuccess(String toast, int type, Object info) throws Exception {
                super.onSuccess(toast, type, info);
                show(MainActivity.class);
                sendBroadcast(new Intent(MainActivity.SWICH_FRAGMENT));
                finish();
            }

            @Override
            public void onEnd(String toast, int type) throws Exception {
                super.onEnd(toast, type);
                if (!TextUtils.isEmpty(toast)) GetToast.useString(cnt, toast);
            }
        }).execute(cnt);//调接口
    }

    private void getData() {
        new GetChooseDriverInfo(AppContext.myPreferences.getUid(), getIntent().getStringExtra("orderid"), new AsyCallBack<GetChooseDriverInfo.Info>() {
            @Override
            public void onSuccess(String toast, int type, GetChooseDriverInfo.Info info) throws Exception {
                super.onSuccess(toast, type, info);
                list.clear();
                list.addAll(info.list);

            }

            @Override
            public void onEnd(String toast, int type) throws Exception {
                super.onEnd(toast, type);
                adapter.updateListView(list);
            }
        }).execute(cnt, false);//调接口

    }

    private void chooseDiver() {
        new GetChooseDiver(AppContext.myPreferences.getUid(), getIntent().getStringExtra("orderid"), list.get(tposition).getDriverId(), new AsyCallBack<Object>() {
            @Override
            public void onSuccess(String toast, int type, Object info) throws Exception {
                if ("1".equals(info)) {
                    Bundle bundle = new Bundle();
                    bundle.putString("spoint", getIntent().getStringExtra("spoint"));
                    bundle.putString("dpoint", list.get(tposition).getPoint());
                    bundle.putString("orderid", getIntent().getStringExtra("orderid"));
                    show(OrderReceivedActivity.class, bundle);
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("type", "2");
                    jsonObject.put("orderid", getIntent().getStringExtra("orderid"));
                    YunAction.getInstance().sendMessage(SelectDriverActivity.this, list.get(tposition).getDriverId(), jsonObject.toString());
                    finish();
                }

                if (OrderManagementFragment.onRefreshOrderData!= null)
                {
                    OrderManagementFragment.onRefreshOrderData.onRefresh();
                }
            }

            @Override
            public void onEnd(String toast, int type) throws Exception {
                super.onEnd(toast, type);
                if (!TextUtils.isEmpty(toast)) GetToast.useString(cnt, toast);
            }
        }).execute(cnt);//调接口
    }

    @Override
    public void onBackPressed() {

        new AffirmDialog(cnt, "离开该页面，系统将自动为您分配司机，是否离开？", "取消", "离开", R.style.MyDialog) {

            @Override
            protected void onYesClick() {
               // new Intent(MainActivity.SWICH_FRAGMENT);
                autoSelectDriver();
            }
        }.show();
    }

    private void autoSelectDriver() {

        new GetAutoSelectDriver(AppContext.myPreferences.getUid(), getIntent().getStringExtra("orderid"), new AsyCallBack<Object>() {
            @Override
            public void onSuccess(String toast, int type, Object info) throws Exception {
                super.onSuccess(toast, type, info);
                showOrderFragment();
            }

            @Override
            public void onEnd(String toast, int type) throws Exception {
                super.onEnd(toast, type);
                if (!TextUtils.isEmpty(toast)) GetToast.useString(cnt, toast);
            }
        }).execute(cnt);//调接口

    }

    private void showOrderFragment() {
        show(MainActivity.class);
        sendBroadcast(new Intent(MainActivity.SWICH_FRAGMENT));
        finish();
    }

    private void registerReceiver() {
        mReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {

                String action = intent.getAction();
                if (action == null) {
                    return;
                }
                if (action.equals(REFRESH)) {
                    getData();
                }
            }
        };

        // 动态注册广播
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(REFRESH);
        registerReceiver(mReceiver, intentFilter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mReceiver != null) {
            unregisterReceiver(mReceiver);
        }
    }
}
